package com.shyroke.daydayzhuanweb.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.shyroke.daydayzhuanapi.constant.ProjectConst;
import com.shyroke.daydayzhuanapi.constant.ProjectFromConstant;
import com.shyroke.daydayzhuanapi.dto.*;
import com.shyroke.daydayzhuanapi.entity.*;
import com.shyroke.daydayzhuandao.respository.NewsRepository;
import com.shyroke.daydayzhuandao.respository.ProjectRepository;
import com.shyroke.daydayzhuandao.respository.ProjectSubjectRepository;
import com.shyroke.daydayzhuandao.respository.SubjectRepository;
import com.shyroke.daydayzhuansvc.manager.ProjectManager;
import com.shyroke.daydayzhuansvc.service.ICommentService;
import com.shyroke.daydayzhuansvc.service.impl.AppService;
import com.shyroke.daydayzhuansvc.service.impl.ProjectService;
import com.shyroke.daydayzhuansvc.service.impl.SubjectService;
import com.shyroke.daydayzhuansvc.service.impl.UserService;
import com.shyroke.daydayzhuansvc.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类名 ：文章的控制层
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/12/5 11:47
 */
@Controller
@RequestMapping(value = "article")
public class ArticleController {

    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private NewsRepository newsRepository;
    @Autowired
    private AppService appService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private ProjectSubjectRepository projectSubjectRepository;
    @Autowired
    private ProjectManager projectManager;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 跳转到文章详情页面
     * @param projectId 文章id
     * @param model
     * @return
     */
    @GetMapping(value = "desc/{typeId}/{projectId}")
    public ModelAndView desc(@PathVariable("projectId")Integer projectId, ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        response.setStatus(301);
        response.setHeader("Location", "https://www.daydayzhuan.com/article/"+projectId);
        return null;
    }

    /**
     * 跳转到文章详情页面
     * @param projectId 文章id
     * @param model
     * @return
     */
    @GetMapping(value = "/{projectId}")
    public ModelAndView desc3( @PathVariable("projectId")Integer projectId, ModelAndView model, HttpServletRequest request, HttpServletResponse response,
                               @RequestParam(required = false) String channel) throws UnsupportedEncodingException {
        Optional<ProjectEntity> optionalProject = projectRepository.findById(projectId);
        if(!optionalProject.isPresent()){
            model.setViewName("error/404");
            response.setStatus(HttpStatus.SC_NOT_FOUND);
            return model;
        }
        ProjectEntity project = optionalProject.get();
        project.setContent(EmojiTransferUtil.emojiDecode(project.getContent()));
        TypeEntity type = project.getTypeObj();
        model = UserUtils.getMenuList(model,type.getId());
        projectManager.updateReadAmount(request, projectId, channel);
        if(project != null){
            if(project.getCreateTime()!=null){
                project.setShowCreateTime(CommonUtil.getDateByFormat(project.getCreateTime(),"yyyy-MM-dd"));
                model.addObject("pubdate", DateUtils.format(project.getCreateTime(),"yyyy-MM-dd'T'HH:mm:ss"));
            }
            if(project.getUpdateTime() != null){
                model.addObject("update",DateUtils.format(project.getUpdateTime(),"yyyy-MM-dd'T'HH:mm:ss"));
                model.addObject("showUpdateTime",DateUtils.format(project.getUpdateTime(),"yyyy-MM-dd"));
                long days = DateUtil.between(project.getUpdateTime(), new Date(), DateUnit.DAY);
                model.addObject("days",days);
            }
        }
        //3、获取相同标签的文章的前十个文章
        List<ProjectEntity> likeProjects = projectService.getLikeLabelProjectList(projectId,type.getId());
        this.getProjectUrl2(likeProjects);

        //4、获取最新更新的10片（不包含网赚闲谈）
        List<ProjectEntity> newProject = projectService.getTopProject(10);
        this.getProjectUrl2(newProject);
        //获取上一篇和下一篇
        List<ProjectNextPreDto> projectList = projectService.getNextAndPre(projectId);
        for(ProjectNextPreDto project1:projectList){
            if(project1.getId() > projectId){
                model.addObject("next",project1);
            }else{
                model.addObject("pre",project1);
            }
        }
        if(project.getSource()!= null && project.getSource().equals(ProjectFromConstant.NORMAL)){
            //获取最近3篇进展
            List<ProcessProjectDto> processList = projectService.getProcessById(project.getId());
            model.addObject("processList",processList);

            //获取变现反馈
            //最新反馈6条
            List<ProcessProjectDto> withDrawList = projectService.getWithDrawListHome(project.getId());
            model.addObject("withDrawList",withDrawList);
        }
        String content = project.getContent();
        Document document = Jsoup.parse(content);
        Elements imgEles = document.select("img");
        String imgList = "";
        if(imgEles != null && imgEles.size() > 0){
            imgList = imgEles.stream()
                    .map(e -> e.attr("src"))
                    .filter(src -> StringUtils.isNotBlank(src))
                    .collect(Collectors.joining("||"));
        }

        if(StringUtils.isNotBlank(project.getSummary())){
            String summary = Jsoup.parse(project.getSummary()).text();
            project.setSummary(summary);
            String url = "https://www.daydayzhuan.com/article/"+project.getId();
            int count = 100 - url.length() - 1;
            String newSummary = summary;
            if(summary.length() > count) {
                newSummary = newSummary.substring(0,count)+"...";
            }
            project.setShowSinaSummary(newSummary);
        }

        List<ProjectSubjectEntity> relationIdList = projectSubjectRepository.findByProjectId(projectId);
        if (CollectionUtil.isNotEmpty(relationIdList)) {
            Optional<ProjectSubjectEntity> first = relationIdList.stream().sorted(Comparator.comparing(ProjectSubjectEntity::getSubjectId).reversed()).collect(Collectors.toList()).stream().findFirst();
            if (first.isPresent()) {
                Integer subjectId = first.get().getSubjectId();
                SubjectDto subjectDto = subjectService.findNoContentById(subjectId);
                if(subjectDto != null){
                    model.addObject("subjectDto",subjectDto);
                }
            }
        }
        //获取评论信息
        List<CommentDto> commentList = commentService.getComment(projectId);
        //获取投稿用户信息
        model.addObject("commitUserInfo",userService.findById(project.getCreateId()));
        model.addObject("commitInfo",userService.getCommitInfo(project.getCreateId()));
        model.addObject("likeProjects",likeProjects);
        model.addObject("newProject",newProject);
        model.addObject("type",type);
        model.addObject("project",project);
        model.addObject("imgList",imgList);
        model.addObject("channel", StrUtil.isBlank(channel)?"PC":channel);
        model.addObject("commentInfoList",commentList);
        model.addObject("qrcode","https://daydayzhuan.oss-cn-shenzhen.aliyuncs.com/img/inviteImg/goods.png");
        model.setViewName("article/desc");
        return model;
    }

    /**
     * 跳转到文章详情页面
     * @param projectId 文章id
     * @param model
     * @return
     */
    @GetMapping(value = "desc/{projectId}")
    public ModelAndView desc2(@PathVariable("projectId")Integer projectId, ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        response.setStatus(301);
        response.setHeader("Location", "https://www.daydayzhuan.com/article/"+projectId);
        return null;
    }

    /**
     * 保存评论
     * @param comment
     * @return
     */
    @RequestMapping(value = "saveComment")
    @ResponseBody
    public R saveComment(CommentDto comment){
        if(comment.getArticleId() == null || StringUtils.isAnyBlank(comment.getContent(),comment.getUserName(),comment.getEmail())){
            return R.error("请填写完整信息！");
        }
        if(comment.getReplyForId() == null){
            comment.setReplyForId(0);
        }else{
            //获取该评论的楼主
            List<CommentEntity> commentList  = commentService.getCommentByProjectId(comment.getArticleId());
            Integer replyParentId = this.getReplyParentId(comment.getReplyForId(),commentList);
            comment.setReplyForId(replyParentId);
        }

        //设置为未审核
        comment.setImage("/img/user.png");
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        try {
            commentService.insert(comment);

            Optional<ProjectEntity> optionalProject = projectRepository.findById(comment.getArticleId());
            if(optionalProject.isPresent()){
                ProjectEntity project = optionalProject.get();
                NewsEntity news = new NewsEntity();
                news.setContent("有用户新评论啦，评论内容："+comment.getContent());
                news.setType("1");
                news.setDate(new Date());
                news.setIsRead(0);
                news.setUserId(project.getCreateId());
                newsRepository.save(news);

                return R.ok("发表评论成功！审核后即可看见！");
            }
            return R.error("评论的文章找不到，id:"+comment.getArticleId());
        }catch (Exception e){
            logger.info("保存异常",e);
            return  R.error("保存失败！");
        }
    }

    private Integer getReplyParentId(Integer replyForId, List<CommentEntity> commentList) {

        Integer result = null;

        for(CommentEntity comment:commentList){
            if(comment.getId().equals(replyForId)){
                replyForId = comment.getReplyForId();
                result =  comment.getId();
            }
        }

        if(replyForId !=  0){
            result = getReplyParentId(replyForId,commentList);
        }


        return result;

    }


    /**
     * 获取评论列表
     * @param page
     * @param projectId
     * @return
     */
    @RequestMapping(value = "getComment")
    @ResponseBody
    public TabelData<CommentDto> getComment(Page page,@RequestParam("projectId") Integer projectId){
        return  commentService.getComment(page,projectId);
    }


    @PostMapping("updateCount")
    @ResponseBody
    public void updateCount(@RequestParam("projectId") Integer projectId){
        projectService.updateCount(projectId);
    }


    @PostMapping("like")
    @ResponseBody
    public void like(@RequestParam("id")Integer id,HttpServletRequest request){
        projectService.like(id,request);
    }

    @PostMapping("dip")
    @ResponseBody
    public void dip(@RequestParam("id")Integer id,HttpServletRequest request){
        projectService.dip(id,request);
    }


    private void getProjectUrl(List<ProjectDto> likeProjects) {

        if(likeProjects != null && likeProjects.size()>0){
            for(ProjectDto project:likeProjects){
                if(ProjectConst.BAOPEI_PROJECT.equals(project.getType())){
                    //包赔项目
                    project.setUrl("/article/baopei_desc/"+project.getTypeObj().getId()+"/"+project.getId());
                }else{
                    //撸羊毛/长期/投资项目
                    project.setUrl("/article/"+project.getId());
                }

            }
        }
    }

    private void getProjectUrl2(List<ProjectEntity> likeProjects) {
        if(likeProjects != null && likeProjects.size()>0){
            for(ProjectEntity project:likeProjects){
                if(ProjectConst.BAOPEI_PROJECT.equals(project.getType())){
                    //包赔项目
                    project.setUrl("/article/baopei_desc/"+project.getTypeObj().getId()+"/"+project.getId());
                }else{
                    //撸羊毛/长期/投资项目
                    project.setUrl("/article/"+project.getId());
                }

            }
        }
    }
}


